package com.xhh.nphm.common.utils;

import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtil2
{
  private static String username;
  private static String password;
  private static String url;
  private static String driver;

  private static ThreadLocal<Connection> tl = new ThreadLocal();

  static {
    Properties p = new Properties();
    try {
      p.load(DBUtil2.class.getClassLoader()
        .getResourceAsStream("jdbc2.properties"));
      username = p.getProperty("jdbc2.username");
      password = p.getProperty("jdbc2.password");
      url = p.getProperty("jdbc2.url");
      driver = p.getProperty("jdbc2.driverClassName");
      Class.forName(driver);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(
        "关闭数据库连接失败！");
    }
  }

  public static Connection getConnection()
  {
    Connection con = (Connection)tl.get();
    if (con == null) {
      try {
        con = DriverManager.getConnection(
          url, username, password);
        tl.set(con);
      } catch (SQLException e) {
        e.printStackTrace();
        throw new RuntimeException(
          "关闭数据库连接失败！");
      }
    }
    return (Connection)tl.get();
  }

  public static void closeConnection()
  {
    Connection con = (Connection)tl.get();
    if (con != null)
      try {
        con.close();
        tl.set(null);
      } catch (SQLException e) {
        e.printStackTrace();
        throw new RuntimeException(
          "关闭数据库连接失败！");
      }
  }

  public static void main(String[] args) throws Exception
  {
    System.out.println(getConnection());
  }
}

